import request from '@/utils/request'
import pinyin from 'pinyin'
// 获取歌手分类列表
export const getSingerList = (
  params: Partial<IGetSingerListParams> = {
    offset: 1,
    limit: 100,
    area: -1,
    type: -1
  }
): Promise<{
  code: number
  data: { title: string; list: ISingerItem[] }[]
}> => {
  return request<IGetSingerListRes>(`/artist/list`, params).then((result) => {
    const HOT_NAME = '热'
    const singerMap: {
      [key: string]: { title: string; list: ISingerItem[] }
    } = {
      hot: {
        title: HOT_NAME,
        list: result.artists.slice(0, 20)
      }
    }
    result.artists.slice(20).forEach((item) => {
      const key = pinyin(item.name)[0][0].slice(0, 1).toUpperCase()
      if (key) {
        if (!singerMap[key]) {
          singerMap[key] = {
            title: key,
            list: []
          }
        }
        // 每个字母下面会有多名歌手
        singerMap[key].list.push(item)
      }
    })

    // 热门歌手
    const hot: { title: string; list: ISingerItem[] }[] = []
    // 字母歌手
    const letter: { title: string; list: ISingerItem[] }[] = []

    // 遍历处理 singerMap，让结果有序
    for (const key in singerMap) {
      const item = singerMap[key]
      if (item.title.match(/[a-zA-Z]/)) {
        letter.push(item)
      } else if (item.title === HOT_NAME) {
        hot.push(item)
      }
    }
    // 按字母顺序排序
    letter.sort((a, b) => {
      return a.title.charCodeAt(0) - b.title.charCodeAt(0)
    })
    return {
      code: 200,
      data: hot.concat(letter)
    }
  })
}

// 获取歌手全部歌曲
/**
 *
 * @param id {number} 歌手id
 * @param offset {number} 第几页
 * @param limit {number} 一页多少条
 */
export const getSingerSongs = (id: number, offset: number = 1, limit: number = 100) =>
  request<{
    songs: ISongItem[]
    more: boolean
    total: number
    code: number
  }>(`/artist/songs?id=${id}&offset=${offset}&limit=${limit}`)

export const getSongDetail = (ids: number[]) =>
  request<{ songs: ISongItem[] }>(`/song/detail?ids=${ids.join(',')}`)
